package com.robotic.udp;

import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

@Component
public class UdpCommandSender {

    private final DatagramSocket socket;

    public UdpCommandSender() throws SocketException {
        // 创建一个socket供整个应用使用
        this.socket = new DatagramSocket();
    }

    public void sendCommand(String host, int port, int commandCode, int value) {
        try {
            InetAddress address = InetAddress.getByName(host);
            ByteBuffer buffer = ByteBuffer.allocate(12);
            buffer.order(ByteOrder.LITTLE_ENDIAN); // 关键：小端字节序

            buffer.putInt(commandCode);
            buffer.putInt(value);
            buffer.putInt(0); // 简单指令类型为0

            byte[] payload = buffer.array();
            DatagramPacket packet = new DatagramPacket(payload, payload.length, address, port);
            socket.send(packet);
        } catch (IOException e) {
            // 在生产环境中应记录日志
            System.err.println("发送UDP指令失败: " + e.getMessage());
        }
    }
}
